#!/bin/bash

IMAGE_FILE=fat32-image
MOUNT_DIR=fat32-image-dir
IMAGE_SIZE=$1
SOURCE_DIR=$2

if [ -z "$IMAGE_SIZE" -o -z "$MOUNT_DIR" ]; then
    echo "USAGE: $0 image_size_in_MB source_directory"
    exit 1
fi

[ `id -u` == 0 ] || (echo "You must run this script as root."; exit 1) || exit 1
[ -d $SOURCE_DIR ] || (echo "Specified source directory doesn't exist: $SOURCE_DIR"; exit 1) || exit 1
[ -e $IMAGE_FILE ] && rm -f $IMAGE_FILE

# make empty image
echo "-> Creating empty image..."
dd if=/dev/zero of=$IMAGE_FILE bs=1048576 count=$IMAGE_SIZE || exit 1

# setup loop device to image
echo "-> Setting up loop device..."
LOOP_DEV=`losetup --show -f fat32-image`
if [ -z "$LOOP_DEV" ]; then
    echo "ERROR setting up loop device"
    exit 1
fi

# make filesystem on image
echo "-> Formatting image as FAT32..."
mkdosfs -F 32 $LOOP_DEV || exit 1

# mount image
echo "-> Mounting image..."
[ -d $MOUNT_DIR ] || mkdir $MOUNT_DIR
mount -t vfat $LOOP_DEV $MOUNT_DIR || exit 1

# copy files
echo "-> Copying files to image..."
cp -r $SOURCE_DIR/* $MOUNT_DIR

# cleanup
echo "-> Cleaning up..."
umount $LOOP_DEV
rmdir $MOUNT_DIR
losetup -d $LOOP_DEV

echo "-> Done."